<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购单号" prop="caigouDanhao">
        <el-input
          v-model="queryParams.caigouDanhao"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购日期" prop="caigouDate">
        <el-date-picker clearable
                        v-model="queryParams.caigouDate"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>

      </el-form-item>
    </el-form>
    <el-table :summary-method="getSummaries" show-summary v-loading="caiLoading" :data="caigouList" >
      <el-table-column label="采购单号" width="150" align="center" prop="caigouDanhao">
        <template slot-scope="scope">
          <div style="cursor:pointer;text-decoration:underline;color: blue" @click="rowClickInfo(scope.row)">{{ scope.row.caigouDanhao }}</div>
        </template>
      </el-table-column>
      <el-table-column label="采购日期" width="120" align="center" prop="caigouDate"  />
      <el-table-column label="物料名称" width="200" align="center" prop="itemName"  />
      <el-table-column label="物料编号" width="100" align="center" prop="itemCode"  />
      <el-table-column label="物料分类" width="150" align="center" prop="className"  />
      <el-table-column label="规格" width="150" align="center" prop="spec"  />
      <el-table-column label="单位" width="150" align="center" prop="unit"  />
      <el-table-column label="采购数量" width="80" align="center" prop="caigouNum"  />
      <el-table-column label="单价（元）" width="100" align="center" prop="unitPrice" >
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.unitPrice | numFilter}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="总价（元）"  align="center" prop="totalPrice">
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.unitPrice*scope.row.caigouNum | numFilter}}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--    采购单详情-->
    <el-dialog :close-on-click-modal="false" :title="jsTitle" :visible.sync="jsOpen"  width="800px" append-to-body>
      <button v-print="printObj">打印</button>
      <div id="main1" style="width: 100%">
        <div style="width: 100%;text-align: center;font-size: 24px;margin-bottom:5px;">数字智能制造平台</div>
        <div style="width: 100%;text-align: center;font-size: 20px;margin-bottom:10px;">采购结算单</div>
        <el-table :data="caigouList">
          <el-table-column label="采购单号" width="80" align="center" prop="caigouDanhao"  />
          <el-table-column label="物料名称" width="80" align="center" prop="itemName"  />
          <el-table-column label="物料编号" width="80" align="center" prop="itemCode"  />
          <el-table-column label="规格" width="60" align="center" prop="spec"  />
          <el-table-column label="供应商" width="80" align="center" prop="supplyName"  />
          <el-table-column label="物料分类" width="60" align="center" prop="className"  />
          <el-table-column label="采购数量" width="60" align="center" prop="caigouNum"  />
          <el-table-column label="单位" width="50" align="center" prop="unit"  />
          <el-table-column label="单价（元）" width="60" align="center" prop="unitPrice"  />
          <el-table-column label="总价（元）" width="60" align="center" prop="totalPrice"  />
          <el-table-column label="采购日期" width="80" align="center" prop="caigouDate"  />
<!--          <el-table-column label="经办人" width="150" align="center" prop="createBy"  />-->
        </el-table>
        <div style="text-align: right"><span style="font-size: 18px;font-weight: 800">总数量：</span>{{zsl}}<span style="margin-left: 50px;margin-right: 20px;font-size: 18px;font-weight: 800">总金额：</span><span style="margin-right: 40px;">{{zje}}</span></div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {getListCaigouDetail} from "@/api/business/caigouDetail";
  export default {
    name: "CaigouInfo",
    dicts: ['shenhe_state'],
    data(){
      return {
        printObj: {
          id: "main1",    // 这里是要打印元素的ID
          popTitle: '',  // 打印的标题
          extraCss: '',  // 打印可引入外部的一个 css 文件
          extraHead: ''  // 打印头部文字
        },
        caigouList:[],
        caiLoading:false,
        // 显示搜索条件
        showSearch: true,
        jsOpen:false,
        jsTitle:"结算单",
        zsl:0,
        zje:0,
        caigouDate: '',
        // 表格的高度
        // tableHeight: document.documentElement.scrollHeight - 245 + "px",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          caigouDanhao: null,
          shenqingName: null,
          shenqingDate: null,
          caigouName: null,
          caigouDate: null,
          params: {
            beginTime: null,
            endTime: ''
          },
          shenheState: null,
          totalPrice: null,
          totalNum: null,
        },
      }
    },
    filters: {
      numFilter (value) {
        // 截取当前数据到小数点后两位
        let realVal = parseFloat(value).toFixed(2)
        return realVal
      }
    },
    methods:{
      rowClickInfo(row){
        console.log(row)
        this.jsOpen = true
      },
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计';
            return;
          }
          if (index === 1 || index === 2 || index === 3 || index === 6 || index === 8) {
            return '';
          }
          for(var i=0 ;i<data.length;i++){
            data[i].totalPrice =data[i].caigouNum*data[i].unitPrice;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                if(index==7){
                  return prev + curr
                }else{
                  return this.keepTwoDecimalFull(Number(prev) + curr);
                }
              } else {
                return prev;
              }
            }, 0);
            sums[index];
          } else {
            sums[index] = '';
          }
        });

        return sums;
      },
      keepTwoDecimalFull(num) {
        var result = parseFloat(num);
        if (isNaN(result)) {
          alert('传递参数错误，请检查！');
          return false;
        }
        result = Math.round(num * 100) / 100;
        var s_x = result.toString(); //将数字转换为字符串

        var pos_decimal = s_x.indexOf('.'); //小数点的索引值


        // 当整数时，pos_decimal=-1 自动补0
        if (pos_decimal < 0) {
          pos_decimal = s_x.length;
          s_x += '.';
        }

        // 当数字的长度< 小数点索引+2时，补0
        while (s_x.length <= pos_decimal + 2) {
          s_x += '0';
        }
        return s_x;
      },
      /** 查询采购列表 */
      getList() {
        this.loading = true;
        if(this.queryParams.caigouDate != null && this.queryParams.caigouDate != undefined){
          this.caigouDate = this.queryParams.caigouDate
          this.queryParams.params.beginTime = this.queryParams.caigouDate[0]
          this.queryParams.params.endTime = this.queryParams.caigouDate[1]
          this.queryParams.caigouDate = ''
        }
        getListCaigouDetail(this.queryParams).then(response => {
          this.caigouList = response.data;
          this.zsl = 0
          this.zje = 0
          for(let i=0;i<this.caigouList.length;i++){
            this.zsl += this.caigouList[i].caigouNum
            this.zje += this.caigouList[i].totalPrice
          }
        if(this.caigouDate != '' && this.caigouDate != undefined && this.caigouDate != null){
          this.queryParams.caigouDate = this.caigouDate
          }
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/caigouDetail/export', {
          ...this.queryParams
        }, `采购单报表_${new Date().getTime()}.xlsx`)
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
    }
  }
</script>
<style media="print">
  @page {
    size: landscape;
    margin: 3mm;
  }
  @media print {
    html {
      background-color: #ffffff;
      height: auto;
      margin: 0px;
    }
    body {
      border: solid 1px #ffffff;
      /* margin: 10mm 15mm 10mm 15mm; */
    }
    #main table {
      table-layout: auto !important;
    }
    #main .el-table__header-wrapper .el-table__header {
      width: 100% !important;
      border: solid 1px #f2f2f2;
    }
    #main .el-table__body-wrapper .el-table__body {
      width: 100% !important;
    }
    #main #pagetable table {
      table-layout: fixed !important;
    }
  }
</style>
